import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '../../api'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore(
  'auth',
  () => {
    const router = useRouter()
    const token = ref(localStorage.getItem('token') || '')
    const tokenExpireTime = ref(localStorage.getItem('tokenExpireTime') || '')
    const user = ref(null)
    const isAuthenticated = ref(!!localStorage.getItem('token'))
    const userAvatar = ref(null)

    // 检查 token 是否过期
    const isTokenExpired = () => {
      if (!tokenExpireTime.value) return true
      const now = new Date().getTime()
      const expireTime = parseInt(tokenExpireTime.value)
      const isExpired = now > expireTime

      if (isExpired) {
        console.log('Token expired:', {
          now: new Date(now).toLocaleString(),
          expireTime: new Date(expireTime).toLocaleString()
        })
      }

      return isExpired
    }

    // 设置 token 和过期时间
    const setToken = (newToken) => {
      token.value = newToken
      // 设置24小时过期
      const now = new Date()
      // 直接使用 setTime 设置24小时后的时间戳
      const expireTime = now.getTime() + (24 * 60 * 60 * 1000)

      console.log('Token expiration:', {
        now: new Date().toLocaleString(),
        expireTime: new Date(expireTime).toLocaleString()
      })

      tokenExpireTime.value = expireTime.toString()
      localStorage.setItem('token', newToken)
      localStorage.setItem('tokenExpireTime', expireTime.toString())
    }

    // 清除 token 和过期时间
    const clearToken = () => {
      token.value = ''
      tokenExpireTime.value = ''
      localStorage.removeItem('token')
      localStorage.removeItem('tokenExpireTime')
    }

    // 登录成功后,我需要根据token获取用户信息,并且将用户信息存储到user中,对路由进行鉴权,如果存在token,requiresAuth设置为 false
    const loginApi = async ({ username, password }) => {
      try {
        const response = await api.post('/user/login', {
          username,
          password
        })

        if (response.data.code === 200) {
          // 使用 setToken 设置 token 和过期时间
          setToken(response.data.data.token)
          user.value = response.data.data.user
          isAuthenticated.value = true
          userAvatar.value = 'https://api.dicebear.com/7.x/bottts/svg?seed=' + user.value.username
          ElMessage.success('登录成功')
          await router.push('/chat')
        }
        return response.data
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '登录失败')
        throw error
      }
    }
    const registerApi = async ({ username, password }) => {
      try {
        const response = await api.post('/user/register', {
          username,
          password
        })

        if (response.data.code === 200) {
          // 保存token到localStorage
          localStorage.setItem('token', response.data.data.token)
          // 更新状态
          token.value = response.data.data.token
          user.value = response.data.data.user
          isAuthenticated.value = true
          userAvatar.value = 'https://api.dicebear.com/7.x/bottts/svg?seed=' + user.value.username
          ElMessage.success('注册成功')
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '注册失败')
        throw error
      }
    }
    const logout = async () => {
      // 清除所有认证相关信息
      clearToken()
      user.value = null
      isAuthenticated.value = false
      userAvatar.value = null
      localStorage.removeItem('user')
      ElMessage.success('已退出登录')
      await router.push('/login')
    }
    const setUser = (userData) => {
      user.value = userData
    }

    // 更新用户设置 - 确保不存储敏感信息
    const updateUserSettings = (settings) => {
      if (user.value) {
        user.value = {
          ...user.value,
          theme: settings.theme,
          // 本来想的是,不将API密钥存储在用户对象中,但是后来感觉没有必要,因为API密钥是用户自己的,所以还是存储在用户对象中,如果后期需要修改的话,可能会进行脱敏处理
          api_key: settings.api_key,
          model: settings.model,
          temperature: settings.temperature
        }
      }
    }

    // 获取用户信息
    const fetchUserProfile = async () => {
      try {
        const response = await api.get('/user/profile')
        if (response.data) {
          user.value = response.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
      }
    }

    const updateUserInfo = (user) => {
      user.value = user;

    }

    return {
      token,
      user,
      isAuthenticated,
      loginApi,
      logout,
      setUser,
      updateUserSettings,
      fetchUserProfile,
      userAvatar,
      registerApi,
      updateUserInfo,
      isTokenExpired
    }
  },
  {
    persist: {
      enabled: true,
      strategies: [
        {
          storage: localStorage,
          paths: ['user', 'isAuthenticated', 'userAvatar'],
          excludeKeys: ['token', 'tokenExpireTime']
        }
      ]
    }
  }
)
